<template>
    <rx-dialog ref="dialog" @handOk="handleSubmit" @cancel="cancel">
        <div v-if="mdl.status=='Draft'" slot="toolbar">
            <a-button type="primary" @click="deployNews">{{i18n('form.publish','发布')}}</a-button>
        </div>
        <rx-layout class="ins-news-layout">
            <div slot="center">
                <a-form :form="form" layout="vertical">
                    <a-form-item style="display:none">
                        <a-input v-decorator="['newId']"/>
                    </a-form-item>
                    <a-form-item  :label="i18n('form.publishType','发布类型')">
                        <div style="display: flex;flex-direction: column">
                            <a-select id="sysDicNew" v-model="mdl.sysDicNew"  @change="defChangeType">
                                <a-select-option v-for="item in sysDicNewList" :key="item.value" :value="item.value">
                                    {{ item.name }}
                                </a-select-option>
                            </a-select>
                            <span v-show="columnShow" style="color: red">{{i18n('msa.publishTypeTips','请选择发布类型！')}}</span>
                        </div>
                    </a-form-item>
                    <a-form-item :label="i18n('form.subject','标题')">
                        <a-input :placeholder="i18n('form.subject','标题')" style="width: 100%"
                                 v-decorator="['subject', {rules: [{required: true, message: i18n('form.subject','标题','input')}]}]"/>
                    </a-form-item>
                    <a-form-item  :label="i18n('form.abstract','摘要')">
                        <a-textarea
                            :placeholder="i18n('form.abstract','摘要')" style="width: 100%"
                            v-decorator="['keywords', {rules: [{required: true, message: i18n('form.abstract','摘要','input')}]}]"
                            :auto-size="{ minRows: 2 }"
                        />
                    </a-form-item>


                    <a-form-item  :label="i18n('form.picNotice','带图公告')">
                        <a-upload-dragger
                            class="rx-upload-deagger"
                            :directory="false"
                            :showUploadList="false"
                            action="/api/api-system/system/core/sysFile/upload"
                            :headers="headers"
                            :multiple="false"
                            @change="handleChange"
                        >
                            <template v-if="images[0] && images[0].fileId" >
                                <div class="delImg" @click.stop="delImg"><a-icon type="close-circle" /></div>
                                <img  :src="imageUrl" class="avatar" />
                            </template>
                            <div v-else class="upload-empty">
                                <i class="iconfont iconshangchuan1 upload-empty-icon"></i>
                                <div class="upload-empty-text">
                                        建议上传宽高378px*216px的图片
                                </div>
                            </div>
                        </a-upload-dragger>
                    </a-form-item>


                    <a-form-item  :label="i18n('form.content','内容')">
                        <div style="min-height: 180px;">
                            <quill-editor
                                style="min-height: 180px;"
                                v-model="mdl.content"
                                ref="myQuillEditor"
                                :options="editorOption"
                                @blur="onEditorBlur($event)"
                                @focus="onEditorFocus($event)"
                                @change="onEditorChange($event)">
                            </quill-editor>
                        </div>
                    </a-form-item>
                    <a-form-item  :label="i18n('form.attachment','附件')" style="margin-top: 10px;">
                        <rx-attach-component v-model="fileLists" ref="rxAttach" :showUploadList="true">
                            <div slot="fileList" slot-scope="{ fileList }">
                                <div class="upload-row" :key="file.fileId" v-for="file of fileList">
                                    <div class="uploader-left" :class="setClass(file)">
                                        <div class="file-name">{{file.name}}<span class="iconColor">（{{getSize(file.size)}}）</span></div>
                                        <div class="user-name">
                                            <span>
                                                <my-icon type="iconpeople"/><rx-user-info :userId="file.createBy" />
                                            </span>
                                            <span>
                                                <my-icon type="icontime"/><span>{{file.createTime}}</span>
                                            </span>
                                        </div>
                                    </div>
                                    <div class="uploader-right">
                                        <span class="file-btn-icon"><a-icon v-if="file.fileId" @click="openFile(file,'down')" type="cloud-download" title="下载"/></span>
                                        <span class="file-btn-icon"><a-icon v-if="file.fileId" @click="openFile(file,'preview')" type="eye" title="预览"/></span>
                                        <span class="file-btn-icon"><a-icon type="delete" @click="openFile(file,'del')" title="删除"/></span>
                                    </div>
                                </div>
                            </div>
                        </rx-attach-component>
                    </a-form-item>
                </a-form>
            </div>
        </rx-layout>

    </rx-dialog>
</template>
<script>
import InsNewsApi from '@/api/portal/core/insNews';
import {BaseForm, RxDialog, RxUserInfo,TokenUtil,Util} from "@lowcode/jpaas-common-lib";
import {quillEditor} from 'vue-quill-editor'
import ACol from "ant-design-vue/es/grid/Col";

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
    name: 'InsNewsEdit',
    mixins: [BaseForm],
    components: {
        ACol,RxUserInfo,
        RxDialog,
        quillEditor
    },
    props: {
        prefixCls: {
            type: String,
            default: 'ant-editor-quill'
        },
        value: {
            type: String
        }
    },
    data() {
        return {
            labelCol: {span: 3},
            wrapperCol: {span: 21},
            labelCol1: {span: 6},
            wrapperCol1: {span: 18},

            images: [],
            columnShow: false,
            sysDicNewList: [],
            editorOption: {},
            fileLists: [],
            subItem: {},
            headers:{}
        }
    },
    computed:{
        imageUrl() {
            const fileId = this.images[0].fileId ;
            let accessToken = TokenUtil.getToken();
            return `/api/api-system/system/core/sysFile/downloadScale/${fileId}?accessToken=` + accessToken
        },
    },
    created() {
        this.initHeader()
        this.getInsSysDicNewList();
    },
    methods: {
        delImg(){
            this.images = []
        },
        i18n2(name,text,key){
            return this.$ti18(name,text,"insPortalDef",key);
        },
        handleChange(info) {
            if (info.file.status === 'uploading') {
                this.loading = true
                return
            }
            if (info.file.status === 'done') {
                info.file.fileId = info.file.response.data[0].fileId ;
                this.images = [info.file]
            }
        },
        initHeader() {
            let token = TokenUtil.getToken()
            if (token) {
                this.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
            }
        },
        getSuffix(file) {
            let fileName = file.name;
            if(!fileName){
                return "";
            }
            let indexS = fileName.lastIndexOf(".");
            return fileName.substr(indexS).toLowerCase();
        },
        setClass(file) {
            if (!file) return;
            let extName = this.getSuffix(file);
            let fileType = this.type;
            for (let key in fileType) {
                let type = fileType[key];
                if (type.includes(extName)) {
                    return key + "Box";
                }
            }
            return "otherBox";
        },
        openFile(file,type){
            let obj = {
                down:'openFile',
                preview:'previews',
                del:'del'
            }
            this.$refs['rxAttach'] && this.$refs['rxAttach'][obj[type]](file)
        },
        getSize(bt) {
            if (bt / (1024 * 1024 * 1024) > 1) {
                return (bt / (1024 * 1024 * 1024)).toFixed(1) + "G";
            } else if (bt / (1024 * 1024) > 1) {
                return (bt / (1024 * 1024)).toFixed(1) + "M";
            } else {
                return Math.ceil(bt / (1024)) + "KB";
            }
        },
        i18n(name,text,key){
            return this.$ti18(name,text,"InsNews",key);
        },
        statusText(val){
            if ("Issued" == val) {
                return this.i18n('form.publish','发布');
            }
            return this.i18n('form.draft','草稿');
        },
        deployNews() {
            this.mdl.status = "Issued";
            this.handleSubmit(this.$refs.dialog);
        },
        defChangeType(val) {
            if (val) {
                this.columnShow = false;
            }
        },
        validForm() {
            if (!this.mdl.sysDicNew) {
                this.columnShow = true;
                return false;
            }
            return true;
        },
        getInsSysDicNewList() {
            InsNewsApi.getTopDicByKey().then(data => {
                this.sysDicNewList = data;
            });
        },
        onload_(data) {
            if (typeof (data) == 'undefined') {
                this.mdl = Object.assign({
                    status: "Draft",
                    content: "",
                    readTimes: 0
                });
                this.form.setFieldsValue(this.mdl);
                return;
            }
            if (data.imgFileId) {
                var set = this;
                InsNewsApi.getByFileId(data.imgFileId).then(res=>{
                    var img = {
                        createTime:res.createTime,
                        fileId:res.fileId,
                        size:res.totalBytes,
                        name:res.fileName,
                        createBy:res.createBy,
                        uniqueIdentifier:res.md5

                    }
                    set.images.push(img)
                })
            }
            if (data.files) {
                this.fileLists = JSON.parse(data.files);
            }
        },
        onEditorChange({quill, html, text}) {
            this.$emit('change', html)
        },
        get(id) {
            return InsNewsApi.get(id);
        },
        save(values) {
            values.sysDicNew = this.mdl.sysDicNew;
            values.status = this.mdl.status;
            values.readTimes = this.mdl.readTimes;
            values.content = this.mdl.content;
            if (this.images && this.images.length>0) {
                values.imgFileId = this.images[0].fileId;
            }else {
                values.imgFileId= '';
            }
            if (this.fileLists) {
                let files= []
                 this.fileLists.filter(res=>{
                    let obj = {
                        createBy:res.createBy,
                        createTime:res.createTime,
                        fileId:res.fileId,
                        name:res.name,
                        relativePath:res.relativePath,
                        _prevUploadedSize:res._prevUploadedSize,
                        size:res.size
                    }
                     files.push(obj)
                })
                values.files = JSON.stringify(files);
            }else {
                values.files = '' ;
            }
            return InsNewsApi.save(values);
        }
    }
}
</script>
<style scoped>

.ins-news-layout >>> .ql-editor{
    min-height: 180px;
}
.ins-news-layout >>> .ant-form-item .ant-form-item-label{
    font-weight: bold;
}
.ins-news-layout >>> .ant-form-item{
    margin-bottom: 6px;
}
.avatar-uploader >>> .ant-upload.ant-upload-select-picture-card {
    margin: initial !important;
}

* >>> .ql-snow .ql-picker-label::before {
    vertical-align: top;
}

* >>> .ql-snow .ql-color-picker .ql-picker-label svg,
* >>> .ql-snow .ql-icon-picker .ql-picker-label svg {
    vertical-align: top;
}

.avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;
}

.ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
}

.ins-news-layout .upload-row,
.ins-news-layout >>> .upload-row{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.uploader-right{
    display: flex;
    font-size: 18px;
}
.file-btn-icon{
    display: inline-flex;
    align-items: center;
    justify-content: center;
    position: relative;
    white-space: nowrap;
    padding: 0 10px;
    color: #4d9eff;
}
.file-btn-icon:not(:first-child)::before{
    content: '';
    height: 12px;
    width: 1px;
    top: 50%;
    margin-top: -6px;
    position: absolute;
    background: #4d9eff;
    left: 0;
}
.user-name{
    display: flex;
}
.user-name > span:not(:first-child){
    padding-left: 10px;
}
.user-name > span > i{
    margin-right: 4px;
}
.file-name{
    color: #666666;
    font-size: 14px;
}
.iconColor{
    color: #c0c5cc;
    font-size: 12px;
}
.uploader-left{
    position: relative;
    flex: 1;
    padding-left:34px ;
}
.uploader-left:before{
    content: '';
    left: 0;
    top: 50%;
    margin-top: -15px;
    background-image: url("../../../../image/css_sprites.png");
    background-repeat: no-repeat;
    position: absolute;
    width: 26px;
    height: 30px;
    background-position: -102px -60px;
}

.uploader-left.wordBox:before {
    background-position: -56px -10px;
}

.uploader-left.txtBox:before {
    background-position: -56px -110px;
}

.uploader-left.pdfBox:before {
    background-position: -56px -60px;
}

.uploader-left.excelBox:before {
    background-position: -194px -10px;
}

.uploader-left.rarBox:before {
    background-position: -10px -110px;
}

.uploader-left.zipBox:before {
    background-position: -194px -110px;
}

.uploader-left.imageBox:before {
    background-position: -102px -60px;
}

.uploader-left.mediaBox:before {
    background-position: -148px -110px;
}

.uploader-left.otherBox:before {
    background-position: -102px -110px;
}

.rx-upload-deagger >>> .ant-upload.ant-upload-drag{
    background-color: #eff5ff;
    border:none;
}
.rx-upload-deagger{
    display: inline-flex;
    width: 378px;
    height: 216px;

}
.rx-upload-deagger >>> .ant-upload-btn,
.rx-upload-deagger >>> .ant-upload-drag-container{
    width: inherit;
    height: inherit;
    padding: 0;
    display: inline-flex;
}
.avatar{
    width: 100%;
    height: 100%;
    object-fit: scale-down;
}
.delImg{
    display: none;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 99;
    padding:1px 4px;
}
.rx-upload-deagger:hover .delImg{
    display: block;
}
.delImg:hover{
    color: red;
}
.upload-empty-icon{
    font-size: 28px;
    color: #4d9eff;
}
.upload-empty{
    width: inherit;
    height: inherit;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
</style>
